package controller

import (
	"appengine"
	"appengine/datastore"
	"bytes"
	"entity"
	"github.com/PuerkitoBio/goquery"
	"helper"
	"model"
	"net/http"
	"search"
	"strings"
	"time"
)

func AutoPost(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	c.Infof("------Start Process-----") 

	r.Header.Set("charset", "utf-8")
	w.Header().Set("charset", "utf-8")

	//get parameter
	title := r.FormValue("post[title]")
	category := r.FormValue("post[category]")
	content := r.FormValue("post[content]")
	tags := r.FormValue("post[tags]")

	//generate alias and check exist
	var obj entity.News
	obj.Alias = helper.GenerateAlias(title)
	if !model.CheckExistNews(c, obj.Alias) {
		obj.Title = title

		//parse content
		b := bytes.NewBufferString(content)
		doc, err := goquery.NewDocumentFromReader(b)
		if err != nil {
			c.Errorf(err.Error())
			return
		}
		html, err := doc.Html()
		if err != nil {
			c.Errorf(err.Error())
			return
		} else {
			obj.Content = html
		}

		//get category + check if category is not exist and add
		var tempCategory []string
		var arrayCategory []string
		if category != "" && len(category) > 0 {
			tempCategory = strings.Split(category, ",")
		}

		for _, e := range tempCategory {
			//generate category alias
			cateAlias := helper.GenerateAlias(e)
			var cate entity.Category
			//check if existing category
			err := model.GetCategory(c, cateAlias, &cate)
			if err == datastore.ErrNoSuchEntity {
				//add new category
				cate.Alias = cateAlias
				cate.Title = e
				cate.Description = ""
				cate.ParentAlias = ""
				cate.Level = 1
				cate.Doc = time.Now()
				if err := model.AddCategory(c, cate); err != nil {
					c.Infof(err.Error())
					continue
				}
			} else if err != nil {
				continue
			}
			//add category relationship
			var cateRs entity.CategoryRelationship
			cateRs.ID = cateAlias + "-" + obj.Alias
			cateRs.CategoryAlias = cateAlias
			cateRs.NewsAlias = obj.Alias
			if err := model.AddCategoryRelationship(c, cateRs); err != nil {
				c.Infof(err.Error())
				continue
			}
			tempCategoryStr := cateAlias + "," + e
			arrayCategory = append(arrayCategory, tempCategoryStr)
		}
		obj.Category = arrayCategory

		//get tag
		var tempTag []string
		var arrayTag []string
		if tags != "" && len(tags) > 0 {
			tempTag = strings.Split(tags, ",")
		} else {
			strTag := helper.GenerateTag(doc.Text())
			tempTag = strings.Split(strTag, ",")
		}

		for _, e := range tempTag {
			//generate tag alias
			tagAlias := helper.GenerateAlias(e)
			var tag entity.Tag
			//check if existing tag
			err := model.GetTag(c, tagAlias, &tag)
			if err == datastore.ErrNoSuchEntity {
				//add new tag
				tag.Alias = tagAlias
				tag.Title = e
				tag.Doc = time.Now()
				if err := model.AddTag(c, tag); err != nil {
					c.Infof(err.Error())
					continue
				}
			} else if err != nil {
				continue
			}
			//add tag relationship
			var tagRs entity.TagRelationship
			tagRs.ID = tagAlias + "-" + obj.Alias
			tagRs.TagAlias = tagAlias
			tagRs.NewsAlias = obj.Alias
			if err := model.AddTagRelationship(c, tagRs); err != nil {
				c.Infof(err.Error())
				continue
			}
			tempTagStr := tagAlias + "," + e
			arrayTag = append(arrayTag, tempTagStr)
		}
		obj.Tags = arrayTag

		//get source
		elementLink := doc.Find("a")
		if elementLink != nil {
			s, exists := elementLink.Last().Attr("href")
			if exists {
				obj.Source = s
			}
		}

		//get thumb
		elementImg := doc.Find("img")
		if elementImg != nil {
			s, exists := elementImg.Last().Attr("src")
			if exists {
				obj.Thumb = s
			}
		}

		//set time
		obj.Doc = time.Now()

		//insert news
		if err := model.AddNews(c, obj); err != nil {
			c.Infof(err.Error())
		} else {
			c.Infof("------Insert Datastore Success !-----")
			if err := search.AddNews(c, obj.SearchTranform()); err != nil {
				c.Infof(err.Error())
			} else {
				c.Infof("------Index Success !-----")
			}
		}
	} else {
		c.Infof("News existed !")
		return
	}
}
